package day20.zhiyou100;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class ManyThread {
    static int i = 0;
    public static void main(String[] args) throws Exception{
        ExecutorService threadPool = Executors.newCachedThreadPool();
        // 同步工具类  参数为：当前程序中需要有多少把锁  见名知意
        CountDownLatch countDownLatch = new CountDownLatch(2000);
        // 我想做一个计数器
        for (int k = 0; k < 2000; k++) {// 1000次
            System.out.println(k);
            threadPool.submit(new Runnable() {
                @Override
                public void run() {
                    sum();
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    // 每执行一次countDown()方法就会释放一把锁
                    countDownLatch.countDown();// 解锁
                }
            });
        }
        threadPool.shutdown();
        //countDownLatch.await();//会进入到阻塞状态，直到程序中的所有锁全部解除掉，结束阻塞状态
        System.out.println(i);// 1000  数据安全
    }

    public static /*synchronized*/ void sum() {
        i++;
    }

}
